package fr.alesia.capital.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.alesia.capital.bean.Continent;
import fr.alesia.capital.bean.Pays;
import fr.alesia.capital.bean.comparator.CapitaleComparator;
import fr.alesia.capital.bean.comparator.ContinentComparator;
import fr.alesia.capital.bean.comparator.PaysComparator;
import fr.alesia.capital.dao.PaysDao;
import fr.alesia.capital.factory.DaoFactory;

@SuppressWarnings("serial")
public class RevisionServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		ServletContext context = this.getServletContext();
		
		PaysDao dao = DaoFactory.getPaysDao();
		List<Pays> pays = null;	
		
		String sort = request.getParameter("sort");
		String filter = request.getParameter("filter");
			
		Continent continent = Continent.getContinent(filter);
		if(continent != null){
			pays = dao.getAll(continent);
		}
		else{
			pays = dao.getAll();
		}

		if(sort != null){
			
			if("pays".equals(sort)){
				
				Collections.sort(pays, PaysComparator.getComparator());
			}
			else if("continent".equals(sort)){
				
				Collections.sort(pays, ContinentComparator.getComparator());
			}
			else if("capitale".equals(sort)){
				
				Collections.sort(pays, CapitaleComparator.getComparator());
			}
		}
		else{
			
			Collections.sort(pays, PaysComparator.getComparator());
		}
		
		request.setAttribute("sort", sort);
		request.setAttribute("code", filter);
		request.setAttribute("pays", pays);
		request.setAttribute("continents", Continent.values());
		
		RequestDispatcher dispatcher = context.getRequestDispatcher("/webapp/page/revisions.jsp");
		dispatcher.forward(request, response);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		this.doPost(request, response);
	}
}
